package top.deepdesigner.controller.systemManage;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import top.deepdesigner.annotation.RequiresPermissionsDesc;
import top.deepdesigner.dto.PermissionsDTO;
import top.deepdesigner.pojo.DtsRole;
import top.deepdesigner.service.DtsPermissionService;
import top.deepdesigner.service.DtsRoleService;
import top.deepdesigner.util.*;
import top.deepdesigner.vo.CatVo;
import top.deepdesigner.vo.PermVo;
import top.deepdesigner.vo.UserRoleListVo;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/21 星期三 14:19:47 <br/>
 */
@RestController
@CrossOrigin
@RequestMapping("/admin/role")
public class RoleController {
  @Autowired
  private DtsRoleService roleService;

  @Autowired
  private DtsPermissionService permissionService;

  @Autowired
  ApplicationContext applicationContext;

  @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "获取列表")
  @RequiresPermissions(value = {"admin:role:list"})
  @GetMapping("/list")
  public Object list(@RequestParam HashMap<String, Object> params) {
    Integer page = Integer.parseInt((String) params.get("page"));
    Integer limit = Integer.parseInt((String) params.get("limit"));
    String sort = (String) params.get("sort");
    String order = (String) params.get("order");

    //角色列表VO
    UserRoleListVo userRoleListVo = new UserRoleListVo();
    //获取分页用户角色数量
    Long count = roleService.getRoleCount();
    //获取分页用户角色列表
    List<DtsRole> dtsRoles = roleService.getRoleList(page, limit, sort, order);
    userRoleListVo.setTotal(count);
    userRoleListVo.setItems(dtsRoles);
    return ResponseUtil.ok(userRoleListVo);
  }

  /**
   * 创建角色
   *
   * @param params 参数
   * @return {@link Object}
   */
  @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "添加")
  @RequiresPermissions(value = {"admin:role:create"})
  @PostMapping("/create")
  @Transactional
  public Object create(@RequestBody HashMap<String, Object> params) {
    String desc = (String) params.get("desc");
    String name = (String) params.get("name");

    //添加角色
    DtsRole role = roleService.createRole(name, desc);
    if (role == null) {//角色已存在
      return AdminResponseUtil.fail(AdminResponseCode.ROLE_NAME_EXIST);
    }
    return ResponseUtil.ok(role);
  }

  /**
   * 更新角色
   *
   * @param dtsRole 角色
   * @return {@link Object}
   */
  @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "编辑")
  @RequiresPermissions(value = {"admin:role:update"})
  @PostMapping("/update")
  @Transactional
  public Object update(@RequestBody DtsRole dtsRole) {
    Boolean aBoolean = roleService.updateRole(dtsRole);
    //判断是否修改成功
    if (!aBoolean) {
      return ResponseUtil.fail();
    }
    return ResponseUtil.ok();
  }

  /**
   * 删除角色
   *
   * @param dtsRole 角色
   * @return {@link Object}
   */
  @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "删除")
  @RequiresPermissions(value = {"admin:role:delete"})
  @PostMapping("/delete")
  @Transactional
  public Object delete(@RequestBody DtsRole dtsRole) {
    Boolean aBoolean = roleService.deleteRole(dtsRole.getId());
    //判断是否删除成功
    if (!aBoolean) {
      return ResponseUtil.fail();
    }
    return ResponseUtil.ok();
  }

  /**
   * 获取角色列表
   *
   * @return {@link Object}
   */
  @GetMapping("/options")
  public Object options() {
    List<DtsRole> dtsRoles = roleService.getRoleList();
    List<CatVo> catVos = dtsRoles.stream()
        .map(item -> {
          CatVo catVo = new CatVo();
          catVo.setValue(item.getId());
          catVo.setLabel(item.getName());
          return catVo;
        }).collect(Collectors.toList());
    return ResponseUtil.ok(catVos);
  }

  @GetMapping("/permissions")
  public Object permissions(@RequestParam Integer roleId) {

    //当前系统暂时拥有的权限
    List<Permission> permissions = PermissionUtil.listPermission(applicationContext, "top.deepdesigner");
    Set<String> permissionStrings = PermissionUtil.listPermissionString(permissions);

    List<PermVo> permVos = PermissionUtil.listPermVo(permissions);


    //已经授权过的权限
    Set<String> permissionsByRoleId = permissionService.getPermissionsByRoleId(roleId);
    HashMap<String, Object> map = new HashMap<>();

    //进行过滤，只留下当前系统拥有的权限
    if (permissionsByRoleId.contains("*")) {
      map.put("assignedPermissions", permissionStrings);
    } else {
      Set<String> collect = permissionsByRoleId.stream().filter(permissionStrings::contains).collect(Collectors.toSet());
      map.put("assignedPermissions", collect);
    }
    map.put("systemPermissions", permVos);
    return ResponseUtil.ok(map);
  }

  @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "授权")
  @RequiresPermissions(value = {"admin:role:permissions"})
  @PostMapping("/permissions")
  public Object permissions(@RequestBody PermissionsDTO permissionsDTO) {
    Boolean b = permissionService.updatePermissionByRoleId(permissionsDTO);
    if (b) return ResponseUtil.ok();
    return ResponseUtil.fail();
  }
}
